#!/usr/bin/env python
# -*- coding:utf-8 -*-
# from qcloud_cos import CosConfig
# from qcloud_cos import CosS3Client


# def upload_file(file_object, key, bucket='auction-1251317460', region="ap-chengdu"):
#     secret_id = 'AKIDW3Rgszw84ylQxMzNn7KOJ6kFPSL5c5MU'  # 替换为用户的 secretId
#     secret_key = 'GQSMXmtsjR0QhuIalzTp250nU6digZSD'  # 替换为用户的 secretKey
#     token = None  # 使用临时密钥需要传入 Token，默认为空，可不填
#     scheme = 'https'  # 指定使用 http/https 协议来访问 COS，默认为 https，可不填
#     config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token, Scheme=scheme)
#     # 2. 获取客户端对象
#     client = CosS3Client(config)
#
#     # 3. 上传文件
#     response = client.upload_file_from_buffer(
#         Bucket=bucket,
#         Body=file_object,
#         Key=key
#     )
#     return "https://{0}.cos.{1}.myqcloud.com/{2}".format(bucket, region, key)




def upload_file(file_object, key, bucket='auction-1251317460', region="ap-chengdu"):
    import os
    # from django.http import JsonResponse
    from django.conf import settings
    imageList = file_object
    # 文件类型，可以判断如果不是图片格式则不上传
    file_type = os.path.splitext(imageList.name)[1]
    if not imageList:
        print("上传文件不能为空")
        return
        # return JsonResponse({'status': False, 'error': '上传文件不能为空'})
    file_format = ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.webp', '.tif', '.tiff']
    if file_type.lower() not in file_format:
        print("上传文件类型非图片格式")
        return
        # return JsonResponse({"status": False, "message": "上传文件类型非图片格式"})
    #  获得一个唯一名字：uuid +hash
    new_name = get_random_str()
    # 组合成文件新名字
    new_file_name = new_name + file_type
    MEDIA_ROOT = settings.MEDIA_ROOT
    if not os.path.exists(MEDIA_ROOT):
        os.makedirs(MEDIA_ROOT)
    # 文件路径
    file_path = os.path.join(MEDIA_ROOT, new_file_name)
    # 将网络地址返回给小程序
    return_img = "http://127.0.0.1:8000/media/" + str(new_file_name)
    # 开始写入本地磁盘
    try:
        f = open(file_path, 'wb')
        # 多次写入
        for i in imageList.chunks():
            f.write(i)
        f.close()
        print("上传图片成功")
        # 不能用Response，result.data.status获取不到，result.data是string类型，不是object
        # return Response({"status": True, "message": "上传图片成功","data": file_path})
        # 如果返回的是JsonResponse，小程序要进行解析console.log(JSON.parse(res.data))
        return new_file_name
        # return JsonResponse({"status": True, "message": "上传图片成功",
        #                      "cos_path": return_img, "key": new_file_name})
    except Exception as e:
        print("上传图片失败：", e)
        return
        # return JsonResponse({"status": False, "message": "上传图片失败:" + str(e)})
    # return "https://{0}.cos.{1}.myqcloud.com/{2}".format(bucket, region, key)
# 获取UUID
def get_random_str():
    import hashlib
    import uuid
    """获取UUID"""
    uuid_val = uuid.uuid4()  # UUID('c1127b61-0714-4eab-8fb0-0138b6a84b4c')
    uuid_str = str(uuid_val).encode('utf-8')  # b'c1127b61-0714-4eab-8fb0-0138b6a84b4c'
    md5 = hashlib.md5()  # <md5 _hashlib.HASH object @ 0x00000253D50DCDB0>
    md5.update(uuid_str)
    return md5.hexdigest()  # 'fb8dfbe57e508bc4ade13f1ac4e7212b'

# 删除图片功能
def del_file(file_object):
    file_object.file.close()
    # file_object.delete()
    # 文件路径地址
    print(file_object.path)
    #*# 如果删除专场，则也同时删除本地图片
    import os
    from django.conf import settings
    imagePath = str(file_object)
    MEDIA_ROOT = settings.MEDIA_ROOT
    try:
        # 1f75e5dfcf258de22566433799ce67a1.jpg
        file_path = os.path.join(os.getcwd(), MEDIA_ROOT + imagePath)
        file_path = file_path.replace('/', '\\')
        os.remove(file_path)
    except Exception as e:
        print("图片删除失败：",e)